import { ref } from 'vue'
import { defineStore } from 'pinia'
import { _onLongin } from '@/apis/login'
import { _mergeCart } from '@/apis/cart'
import { userCartStore } from './cartStore'
export const useUserStore = defineStore('user', () => {
  const userInfo = ref({})
  const cartStore = userCartStore()
  // 登录方法
  const getUserInfo = async (data) => {
    const { data: res } = await _onLongin(data)
    userInfo.value = res?.result
    mergeCart()
    cartStore.updateCartNewList()
  }
  const mergeCart = async () => {
    let data = cartStore.cartList.map(item => {
      return {
        skuId: item.skuId,
        selected: item.selected,
        count: item.count,
      }
    })
    await _mergeCart(data)
  }
  // 清空用户存储方法
  const clearUserIfo = () => {
    userInfo.value = {}
    // 退出登录后清除购物车数据
    cartStore.clearCart()
  }
  return { userInfo, getUserInfo, clearUserIfo }
},
  {
    persist: true,
  })
